package com.dkd.day20251109;

import com.dkd.day20250614.ListNode;

public class Solution {
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);

        ListNode answer = reverseList(head);
        while (answer != null) {
            System.out.println(answer.val);
            answer = answer.next;
        }
    }
    public static ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode prev = null;//设置虚拟头节点
        ListNode temp;
        while (head!= null) {
            temp = head.next;//存储头节点的下一节点
            head.next = prev;//头节点链接前驱节点
            prev = head;//前驱节点变原头节点
            head = temp;//头节点变下一节点
        }
        return prev;
    }
}
